<?php
/**
 * index.php     Zhuayi 框架DB抽象类
 *
 * @copyright    (C) 2005 - 2010  Zhuayi
 * @licenes      http://www.zhuayi.net
 * @lastmodify   2010-10-27
 * @author       zhuayi
 * @QQ			 2179942
 */
class db extends zhuayi
{

	/**
	 * 构造函数
	 * @param find $fields 数据库配置文件 
	 */
	function __construct($fields = array())
	{
		extract($fields, EXTR_OVERWRITE);
		
		/* 定义表前缀 */
		define('T', $cookievarpre);
		
		$this->db = new mysql($dbhost, $dbuser, $dbpw, $dbname,$dbcharset, $pconnect);

		
	}
	
	/**
	 * 返回一个数组
	 * @param string $sql SQL语句 
	 * @param find $where  查询条件 各市入下 array('字段'=>'值')
	 * @param string $limit 结果数
	 */
	function fetch_row($sql,$where=array(),$limit='',$order='')
	{
	
		$sql = self::sqls($sql,$where).$order;
		
		
		/* 如果limit为空，则默认返回前30条 */
		if ($limit == null)
		{
		
		}
		elseif (empty($limit))
		{
			$sql .= ' limit 0 , 30'; 
		}
		else
		{
			$limit = explode(',',$limit);
			
			if (empty($limit[0]) || $limit[0] < '1')
			{
				$limit[0] = 0;
			}
			
			if (empty($limit[1]))
			{
				$sql .= ' limit 0,'.$limit[0];
			}
			else
			{
				$sql .= ' limit '.$limit[0].' , '.$limit[1];
			}
		}
		
		return self::query($sql,true);
		
	}
	
	/**
	 * 返回单挑记录
	 * @param string $sql 
	 * @param find $where  查询条件 各市入下 array('字段'=>'值')
	 * @param int $cachetime 缓存时间,如果为空，则调用默认缓存时间
	 */
	function fetch($sql,$where = array())
	{
		
		$sql = self::sqls($sql,$where);
		
		$sql .= " limit  0 , 1";
		
		return self::query($sql,false);
	}
	
	/**
	 * 查询总数
	 * @param string $sql 
	 * @param int $cachetime
	 */
	function maxnum($sql,$where = array())
	{

		
		$sql = self::sqls(array('0'=>'count','sql'=>$sql),$where);
		
		return $this->db->result($this->db->query($sql));
	}
	
	/**
	 * 组合sql
	 * @param find $sql 三种模式
	 * ⑴ 双表联合查询,array('account'=>array('gid','*'),'account_group'=>array('id','group_name'))、
	 * 键值为表名,第一个参数对应的是表之间连接的字段,一般为外键,第二个参数为要读取出来的字段
	 * ⑵ 单表简单查询:直接赋值表名即可
	 * ⑶ 单表或多表联合复杂查询直接写出sql语句
	 * ⑷ 查询总数,如果数组键值0是'count',则直接查处总数
	 */
	function sqls($sql,$where = array())
	{
		
		/* 如果查询的是总数*/
		if ($sql['0'] == 'count')
		{
			$maxnum = 1;
			$sql = $sql['sql'];
		}
		
		if (is_array($sql))
		{
			
			$table = array_keys($sql);
			$sqls = 'select ';
			
			$as = array('a','b','c','d','e','f');
			
			if (empty($maxnum))
			{
				$i=0;
				foreach ($sql as $key=>$val)
				{
					$wheres[] = $as[$i].'.'.$val[0];
					
					if (empty($val[1]))
					{
						$val[1] = '*';
					}
					$sqls .= $as[$i].'.'.$val[1].' ,';
					$i++;
				}
				$sqls = substr($sqls,0,-1);
			}
			else
			{
				$sqls = ' count(*) ';
			}
			$sqls .= " from ";
			
			
			
			foreach ($table as $key=>$val)
			{
				$sqls .= T.$val." as ".$as[$key]." ,";
			}
			
			$sqls = substr($sqls,0,-1);
			
			$sqls .= " where ".implode(' = ',$wheres);
			
			
			foreach ($where as $key=>$val)
			{
				$key = explode('.',$key);
				
				if (!empty($key[1]))
				{
					$key = $key[0].".`".$key[1]."`";
				}
				else
				{
					$key = $key[0];
				}
				
				$sqls .= " and ".$key." = '".$val."'";
			}
			$sql = $sqls;
		}
		else
		{
			$sql = trim($sql);
			if (substr($sql,0,6) != 'select' && substr($sql,0,4) != 'show')
			{
				if (empty($maxnum))
				{
					$sql = "select * from ".T.$sql;
				}
				else
				{
					$sql = "select count(*) from ".T.$sql;
				}
				
				if (count($where)>0)
				{
					$sql .= " where ";
				}
				$sqls = array();
				
				foreach ($where as $key=>$val)
				{
					$key = explode('.',$key);
					
					if (!empty($key[1]))
					{
						$key = $key[0]."`".$key[1]."`";
					}
					else
					{
						$key = $key[0];
					}
					$sqls[] = $key." = '".$val."'";
				}
				$sql .= implode(' and ',$sqls);
				
			}
			
		}
		return $sql;
	}
	
	/**
	 * 查询
	 * @param string $sql  
	 * @param bood true为多条记录,false为单条记录
	 */
	function query($sql,$line = false)
	{
		$reset = $this->db->query($sql);
		
		if ($line=== false)
		{
			$return =  $this->db->fetch_array($reset);
		}
		else
		{
			
			while ($row = $this->db->fetch_array($reset))
			{
				$list[] = $row;
			}
			
			$return =  $list;
		}

		return $return;
	}
	
	/**
	 * 获取表字段
	 *
	 */
	function fields($table,$array)
	{
		
		$reset = $this->query(' show fields from '.T.$table,true);
		
		$fields = array_keys($array);
		
		foreach ($reset as $val)
		{
			if (in_array($val['Field'],$fields))
			{
				$reset2[$val['Field']] = '\''.addslashes($array[$val['Field']]).'\'';
			}
		}
		
		return $reset2;
		
	}
	
	/**
	 * 写入数据
	 *
	 */
	function insert($table,$array,$action ='insert')
	{
		/* 取出非字段的键值  */
		$array = $this->fields($table,$array);
	
		$fields = array_keys($array);
		$value = array_values($array);
		
		$this->db->query($action." into ".T."$table  (`".implode('`,`',$fields)."`) values (".implode(',',$value).")");
		
		return $this->db->insert_id();
	}
	
	/**
	 * 更新数据
	 *
	 */
	function update($table,$array,$where)
	{
		/* 取出非字段的键值  */
		$array = $this->fields($table,$array);
	
		foreach ($array as $key=>$val)
		{
			$field[] = '`'.$key."`=".$val."";
		}

		return $this->db->query("update ".T."$table set ".implode(',',$field)." where ".$where);
	}
	
	/**
	 * 删除数据
	 *
	 * @param string $table 表名
	 * @param string $where 查询条件
	 */
	function delete($table,$where)
	{
		return $this->db->query("delete from ".T."$table where ".$where);
	}

}